<!--
  * 商品分类
  *
-->
<template>
  <a-spin :spinning="treeData.length === 0">
    <a-tree v-model:selectedKeys="selectedKeys" :expandedKeys="selectedKeys" :treeData="treeData" autoExpandParent :fieldNames="{ title: 'cate_name', key: 'id', value: 'id' }" checkStrictly @select="onSelect" />
  </a-spin>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { searchApi } from '@/api/search/search-api'
import { treeToList } from '@/utils/tree-util'
// ----------------------- 分类树的展示 ---------------------
const props = defineProps({
  value: {
    type: Number,
    default: 0
  }
})
const emit = defineEmits(['update:value'])
// 分类树形数据
const treeData = ref<any[]>([])

// 查询分类列表并构建 分类树
const queryList = async () => {
  const res = await searchApi.cateList()
  treeData.value = [
    {
      id: 0,
      cate_name: '全部',
      children: []
    },
    ...res.data
  ]
}
onMounted(queryList)

// 选中分类
const selectedKeys = ref([props.value])
const onSelect = (_: any, info: any) => {
  const cate_id = treeToList([info.node.dataRef]).map(({ id }) => id).join(',')
  emit('update:value', cate_id)
}

// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({
  queryList
})
</script>
